package com.estate.web.controller.eastate;

import java.io.File;
import java.io.IOException;
import java.util.*;
import java.util.stream.Collectors;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.TypeReference;
import com.google.gson.Gson;
import com.estate.common.annotation.RepeatSubmit;
import com.estate.common.utils.StringUtils;
import com.estate.generator.service.QiniuService;
import com.estate.system.domain.SecondHandDetailAndSecondHand;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.EnableAsync;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.*;
import com.estate.common.annotation.Log;
import com.estate.common.enums.BusinessType;
import com.estate.system.domain.SecondHandDetail;
import com.estate.system.service.ISecondHandDetailService;
import com.estate.common.core.controller.BaseController;
import com.estate.common.core.domain.AjaxResult;
import com.estate.common.utils.poi.ExcelUtil;
import com.estate.common.core.page.TableDataInfo;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;

/**
 * 买房详情Controller
 *
 * @author estate
 * @date 2022-05-28
 */
@Controller
@RequestMapping("/system/secondHand/detail")
@CrossOrigin

public class SecondHandDetailController extends BaseController
{
    private String prefix = "system/detail";

    @Autowired
    private ISecondHandDetailService secondHandDetailService;
    @Resource
    private QiniuService qiniuService;

    @RequiresPermissions("system:detail:view")
    @GetMapping()
    public String detail()
    {
        return prefix + "/detail";
    }

    /**
     * 查询买房详情列表
     */

    @PostMapping("/listByid")
    @ResponseBody
    public SecondHandDetailAndSecondHand listByid(SecondHandDetail secondHandDetail)
    {

        SecondHandDetailAndSecondHand secondHandDetailAndSecondHand = secondHandDetailService.selectSecondHandDetailAndSecondHandList(secondHandDetail);
        System.out.println("secondHandDetailAndSecondHand"+secondHandDetailAndSecondHand);

        return secondHandDetailAndSecondHand;
    }

    /**
     * 删除headpic字段的图片
     * @Params fileName文件的名字
     */
    @RequiresPermissions("system:detail:list")
    @PostMapping("/deleteHeadPic")
    @ResponseBody
    public AjaxResult listByid(String fileName)
    {
        System.out.println("listByid");
        return new AjaxResult();
    }



    /**
     * 导出买房详情列表
     */
    @RequiresPermissions("system:detail:export")
    @Log(title = "买房详情", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    @ResponseBody
    public AjaxResult export(SecondHandDetail secondHandDetail)
    {
        List<SecondHandDetail> list = secondHandDetailService.selectSecondHandDetailList(secondHandDetail);
        ExcelUtil<SecondHandDetail> util = new ExcelUtil<SecondHandDetail>(SecondHandDetail.class);
        return util.exportExcel(list, "买房详情数据");
    }

    /**
     * 新增买房详情
     */
    @GetMapping("/add")
    public String add()
    {
        return prefix + "/add";
    }

    /**
     * 新增保存买房详情
     */
    @RequiresPermissions("system:detail:add")
    @Log(title = "买房详情", businessType = BusinessType.INSERT)
    @PostMapping("/updateSave")
    @ResponseBody

    public AjaxResult updateSave(SecondHandDetail secondHandDetail)
    {

        //如果是数据库中没有数据则直接插入数据,如果有数据,就更新数据,图片变成json对象
        //应该我后端来处理比较方便,我先去查询数据库的json字符串,转为list,然后addlist,没有字符串
        //则生成一个空的list
        //前端应该给我个id,我查查byid有没有数据
        if(secondHandDetailService.selectSecondHandDetailById(secondHandDetail.getId())==null){
            return toAjax(secondHandDetailService.insertSecondHandDetail(secondHandDetail));
        }else{
            return toAjax(secondHandDetailService.updateSecondHandDetail(secondHandDetail));
        }



    }

    /**
     * 更新secondHanddetail表的headpic详情图片
     */
    @RequiresPermissions("system:detail:add")
    @Log(title = "买房详情", businessType = BusinessType.INSERT)
    @PostMapping("/updatepicsave")
    @ResponseBody

    public  AjaxResult updatePicSave(@RequestPart("file") MultipartFile file,@RequestParam int id) throws IOException {
        //如果是数据库中没有数据则直接插入数据,如果有数据,就更新数据,图片变成json对象
        //应该我后端来处理比较方便,我先去查询数据库的json字符串,转为list,然后addlist,没有字符串
        //则生成一个空的list
        //前端应该给我个id,我查查byid有没有数据
        synchronized (this){
            SecondHandDetail secondHandDetail = new SecondHandDetail();
            secondHandDetail.setId((long) id);
            System.out.println("----------updatePicSave-----------");
            if (secondHandDetail.getId()==null){
                return new AjaxResult().error().put("msg","传入id不存在");
            }
            //在数据库查出数据
            SecondHandDetail secondHandDetail1 = secondHandDetailService.selectSecondHandDetailById((secondHandDetail.getId()));
            System.out.println(secondHandDetail1);
            //查出来不存在这个id
            if (secondHandDetail1==null){
                return new AjaxResult().error().put("msg","数据库id不存在");
            }

//        System.out.println("secondHandDetail1.getHeadpic()"+secondHandDetail1.getHeadpic());

            //有id没有图片的字符串
            if (secondHandDetail1.getHeadpic().length()==0){
                System.out.println("有id没有图片的字符串");


                ArrayList list=new ArrayList();
//            list.add(secondHandDetail.getHeadpic());
                Gson gson1=new Gson();
                //返回一个文件的名字
                String fileName = qiniuService.saveImageByName(file,"secondHandDetail");
                String subStr=fileName.replaceFirst("http://","//");
                list.add(subStr);
                String myJsonListString=gson1.toJson(list);
                list.add(myJsonListString);
                System.out.println(myJsonListString);

                SecondHandDetail secondHandDetail2=new SecondHandDetail();
                secondHandDetail2.setId(secondHandDetail.getId());
                secondHandDetail2.setHeadpic(myJsonListString);
                int res = secondHandDetailService.updateSecondHandDetail(secondHandDetail2);
                if (res==0){
                    return new AjaxResult().error().put("msg","插入数据库错误");
                }


            }else if(secondHandDetail1.getHeadpic().length()!=0 ){

                //当查询出来的东西不为空时,直接加入数组
                Gson gson = new Gson();
                boolean flagExist=false;
                ArrayList arrayList = gson.fromJson(secondHandDetail1.getHeadpic(), ArrayList.class);
                String fileName = qiniuService.saveImageByName(file,"secondHandDetail");
                String subStr=fileName.replaceFirst("http://","//");
                arrayList.add(subStr);
                //这块是去掉重复的,用不到了
//            Set<String> set = new HashSet<>();
//            set.addAll(arrayList);


                String moreHeadPicJsonString = gson.toJson(arrayList);
                SecondHandDetail secondHandDetail2=new SecondHandDetail();
                secondHandDetail2.setHeadpic(moreHeadPicJsonString);
                secondHandDetail2.setId(secondHandDetail.getId());

                secondHandDetailService.updateSecondHandDetail(secondHandDetail2);
            }
        }








        return new AjaxResult().success().put("msg","插入成功");
    }
    /**
     * 更新secondHanddetail表的detail_pic详情图片
     */
    @RequiresPermissions("system:detail:add")
    @Log(title = "买房详情", businessType = BusinessType.INSERT)
    @PostMapping("/updatedetailpicsave")
    @ResponseBody
    public AjaxResult updateDetailPicSave(@RequestPart("file") MultipartFile file,@RequestParam int id) throws IOException {
        //如果是数据库中没有数据则直接插入数据,如果有数据,就更新数据,图片变成json对象
        //应该我后端来处理比较方便,我先去查询数据库的json字符串,转为list,然后addlist,没有字符串
        //则生成一个空的list
        //前端应该给我个id,我查查byid有没有数据
        synchronized (this){
            SecondHandDetail secondHandDetail = new SecondHandDetail();
            secondHandDetail.setId((long) id);
            System.out.println("----------updatePicSave-----------");
            if (secondHandDetail.getId()==null){
                return new AjaxResult().error().put("msg","传入id不存在");
            }
            //在数据库查出数据
            SecondHandDetail secondHandDetail1 = secondHandDetailService.selectSecondHandDetailById((secondHandDetail.getId()));
            System.out.println(secondHandDetail1);
            //查出来不存在这个id
            if (secondHandDetail1==null){
                return new AjaxResult().error().put("msg","数据库id不存在");
            }

//        System.out.println("secondHandDetail1.getHeadpic()"+secondHandDetail1.getHeadpic());

            //有id没有图片的字符串
            if (secondHandDetail1.getDetailPic().length()==0){
                System.out.println("有id没有图片的字符串");


                ArrayList list=new ArrayList();
//            list.add(secondHandDetail.getHeadpic());
                Gson gson1=new Gson();
                //返回一个文件的名字
                String fileName = qiniuService.saveImageByName(file,"secondHandDetail");
                String subStr=fileName.replaceFirst("http://","//");
                list.add(subStr);
                String myJsonListString=gson1.toJson(list);
                list.add(myJsonListString);
                System.out.println(myJsonListString);

                SecondHandDetail secondHandDetail2=new SecondHandDetail();
                secondHandDetail2.setId(secondHandDetail.getId());
                secondHandDetail2.setDetailPic(myJsonListString);
                int res = secondHandDetailService.updateSecondHandDetail(secondHandDetail2);
                if (res==0){
                    return new AjaxResult().error().put("msg","插入数据库错误");
                }


            }else if(secondHandDetail1.getDetailPic().length()!=0 ){

                //当查询出来的东西不为空时,直接加入数组
                Gson gson = new Gson();
                boolean flagExist=false;
                ArrayList arrayList = gson.fromJson(secondHandDetail1.getDetailPic(), ArrayList.class);
                String fileName = qiniuService.saveImageByName(file,"secondHandDetail");
                String subStr=fileName.replaceFirst("http://","//");
                arrayList.add(subStr);
                //这块是去掉重复的,用不到了
//            Set<String> set = new HashSet<>();
//            set.addAll(arrayList);


                String moreHeadPicJsonString = gson.toJson(arrayList);
                SecondHandDetail secondHandDetail2=new SecondHandDetail();
                secondHandDetail2.setDetailPic(moreHeadPicJsonString);
                secondHandDetail2.setId(secondHandDetail.getId());

                secondHandDetailService.updateSecondHandDetail(secondHandDetail2);
            }


        }








        return new AjaxResult().success().put("msg","插入成功");
    }

    @RequiresPermissions("system:detail:add")
    @Log(title = "买房详情视频上传", businessType = BusinessType.INSERT)
    @PostMapping("/updatedetailvideosave")
    @ResponseBody
//    @RepeatSubmit
    public AjaxResult updateDetailVideoSave(@RequestPart("file") MultipartFile file,@RequestParam int id) throws IOException {
        System.out.println("得到视频名称"+id);
        //如果是数据库中没有数据则直接插入数据,如果有数据,就更新数据,图片变成json对象
        //应该我后端来处理比较方便,我先去查询数据库的json字符串,转为list,然后addlist,没有字符串
        //则生成一个空的list
        //前端应该给我个id,我查查byid有没有数据
        synchronized (this) {
            SecondHandDetail secondHandDetail = new SecondHandDetail();
            secondHandDetail.setId((long) id);
            System.out.println("----------updatePicSave-----------");
            if (secondHandDetail.getId() == null) {
                return new AjaxResult().error().put("msg", "传入id不存在");
            }
            //在数据库查出数据
            SecondHandDetail secondHandDetail1 = secondHandDetailService.selectSecondHandDetailById((secondHandDetail.getId()));
            System.out.println(secondHandDetail1);
            //查出来不存在这个id
            if (secondHandDetail1 == null) {
                return new AjaxResult().error().put("msg", "数据库id不存在");
            }

//        System.out.println("secondHandDetail1.getHeadpic()"+secondHandDetail1.getHeadpic());

            //有id没有图片的字符串
            if (secondHandDetail1.getVideoAddress().equals("[]")) {
                System.out.println("有id但是 没有视频在数据库");


                ArrayList list = new ArrayList();
//            list.add(secondHandDetail.getHeadpic());
                Gson gson1 = new Gson();
                //返回一个文件的名字
                String fileName = qiniuService.saveImageByName(file, "secondHandDetail");
                String subStr=fileName.replaceFirst("http://","//");
                list.add(subStr);
                String myJsonListString = gson1.toJson(list);
                list.add(myJsonListString);
                System.out.println(myJsonListString);

                SecondHandDetail secondHandDetail2 = new SecondHandDetail();
                secondHandDetail2.setId(secondHandDetail.getId());
                secondHandDetail2.setVideoAddress(myJsonListString);
                int res = secondHandDetailService.updateSecondHandDetail(secondHandDetail2);
                if (res == 0) {
                    return new AjaxResult().error().put("msg", "插入数据库错误");
                }


            } else if (secondHandDetail1.getVideoAddress().length() != 0) {

                //当查询出来的东西不为空时,直接加入数组
                Gson gson = new Gson();
                boolean flagExist = false;
                ArrayList arrayList = gson.fromJson(secondHandDetail1.getVideoAddress(), ArrayList.class);
                String fileName = qiniuService.saveImageByName(file, "secondHandDetail");
                String subStr=fileName.replaceFirst("http://","//");
                arrayList.add(subStr);
                //这块是去掉重复的,用不到了
//            Set<String> set = new HashSet<>();
//            set.addAll(arrayList);


                String moreHeadVideoJsonString = gson.toJson(arrayList);
                SecondHandDetail secondHandDetail2 = new SecondHandDetail();
                secondHandDetail2.setVideoAddress(moreHeadVideoJsonString);
                secondHandDetail2.setId(secondHandDetail.getId());

                int i = secondHandDetailService.updateSecondHandDetail(secondHandDetail2);

                if (i > 0) {
                    return new AjaxResult().success().put("msg", "插入成功");
                }

            } else {
                System.out.println("其他情况");
            }


        }



        return new AjaxResult().success().put("msg","插入失败");
    }
    /**
     * 删除指定picHead图片地址显示
     *
     */
    @RequiresPermissions("system:detail:add")
    @Log(title = "买房详情", businessType = BusinessType.INSERT)
    @PostMapping("/deleteHeadpic")
    @ResponseBody
    @Transactional
    public AjaxResult deleteHeadpic(int id,String fileName) throws IOException {
        //先删除数据库的图片数据
        SecondHandDetail secondHandDetail = secondHandDetailService.selectSecondHandDetailById((long) id);
        Gson gson=new Gson();
        ArrayList arrayList = gson.fromJson(secondHandDetail.getHeadpic(), ArrayList.class);
        arrayList.remove(fileName);
        //已经删除了图片
        String subRes = gson.toJson(arrayList);
        SecondHandDetail newSecondHandDetail=new SecondHandDetail();
        newSecondHandDetail.setId((long) id);
        newSecondHandDetail.setHeadpic(subRes);
        secondHandDetailService.updateSecondHandDetail(newSecondHandDetail);


        //再删除七牛云上的数据
        //从url得到文件名
        File tempFile =new File( fileName.trim());
        String fileName1 = tempFile.getName();
        System.out.println(fileName1);
        //删除
        boolean delQuiniuRes = qiniuService.deletePhoto(fileName1,"secondHandDetail");
        if (delQuiniuRes == false){
            return new AjaxResult().put("error","删除失败");
        }


        return new AjaxResult().put("success","删除成功");


    }

    /**
     * 删除指定detail_pic图片地址显示
     *
     */
    @RequiresPermissions("system:detail:add")
    @Log(title = "买房详情", businessType = BusinessType.INSERT)
    @PostMapping("/deleteDetailDetailpic")
    @ResponseBody
    public AjaxResult deleteDetailHeadpic(int id,String fileName) throws IOException {
        //先删除数据库的图片数据
        SecondHandDetail secondHandDetail = secondHandDetailService.selectSecondHandDetailById((long) id);
        Gson gson=new Gson();
        ArrayList arrayList = gson.fromJson(secondHandDetail.getDetailPic(), ArrayList.class);
        arrayList.remove(fileName);
        //已经删除了图片
        String subRes = gson.toJson(arrayList);
        SecondHandDetail newSecondHandDetail=new SecondHandDetail();
        newSecondHandDetail.setId((long) id);
        newSecondHandDetail.setDetailPic(subRes);
        secondHandDetailService.updateSecondHandDetail(newSecondHandDetail);


        //再删除七牛云上的数据
        //从url得到文件名
        File tempFile =new File( fileName.trim());
        String fileName1 = tempFile.getName();
        System.out.println(fileName1);
        //删除,这里我就换个空间来存放便于管理
        boolean delQuiniuRes = qiniuService.deletePhoto(fileName1,"secondHandDetail");
        if (delQuiniuRes == false){
            return new AjaxResult().put("error","删除失败");
        }


        return new AjaxResult().put("success","删除成功");


    }

    /**
     * 删除指定detail_pic图片地址显示
     *
     */
    @RequiresPermissions("system:detail:add")
    @Log(title = "买房详情", businessType = BusinessType.INSERT)
    @PostMapping("/deleteDetailDetailVideo")
    @ResponseBody
    public AjaxResult deleteDetailHeadVideo(int id,String fileName) throws IOException {

        //先删除数据库的图片数据
        SecondHandDetail secondHandDetail = secondHandDetailService.selectSecondHandDetailById((long) id);
        Gson gson=new Gson();
        ArrayList arrayList = gson.fromJson(secondHandDetail.getVideoAddress(), ArrayList.class);
        arrayList.remove(fileName);
        //已经删除了图片
        String subRes = gson.toJson(arrayList);
        SecondHandDetail newSecondHandDetail=new SecondHandDetail();
        newSecondHandDetail.setId((long) id);
        newSecondHandDetail.setVideoAddress(subRes);
        secondHandDetailService.updateSecondHandDetail(newSecondHandDetail);


        //再删除七牛云上的数据
        //从url得到文件名
        File tempFile =new File( fileName.trim());
        String fileName1 = tempFile.getName();
        System.out.println(fileName1);
        //删除,这里我就换个空间来存放便于管理
        boolean delQuiniuRes = qiniuService.deletePhoto(fileName1,"secondHandDetail");
        if (delQuiniuRes == false){
            return new AjaxResult().put("error","删除失败");
        }


        return new AjaxResult().put("success","删除成功");


    }

    /**
     * 修改买房详情
     */
    @RequiresPermissions("system:detail:edit")
    @GetMapping("/edit/{id}")
    public String edit(@PathVariable("id") Long id, ModelMap mmap)
    {
        SecondHandDetail secondHandDetail = secondHandDetailService.selectSecondHandDetailById(id);
        mmap.put("secondHandDetail", secondHandDetail);
        return prefix + "/edit";
    }

    /**
     * 修改保存买房详情
     */
    @RequiresPermissions("system:detail:edit")
    @Log(title = "买房详情", businessType = BusinessType.UPDATE)
    @PostMapping("/edit")
    @ResponseBody
    public AjaxResult editSave(SecondHandDetail secondHandDetail)
    {
        return toAjax(secondHandDetailService.updateSecondHandDetail(secondHandDetail));
    }

    /**
     * 删除买房详情
     */
    @RequiresPermissions("system:detail:remove")
    @Log(title = "买房详情", businessType = BusinessType.DELETE)
    @PostMapping( "/remove")
    @ResponseBody
    public AjaxResult remove(String ids)
    {
        return toAjax(secondHandDetailService.deleteSecondHandDetailByIds(ids));
    }
}
